package org.linlinjava.litemall.admin.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.annotations.VisibleForTesting;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.admin.beans.FormulaConstants;
import org.linlinjava.litemall.admin.beans.dto.GoodsReviewDto;
import org.linlinjava.litemall.admin.errorcode.ErrorCodeConstants;
import org.linlinjava.litemall.admin.vo.AdminLumiereFormulaVO;
import org.linlinjava.litemall.admin.vo.goods.GoodsFormulaSpecificationsVO;
import org.linlinjava.litemall.core.exception.util.ServiceExceptionUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_UPDATE_NOT_ALLOWED;

/**
 * @auth :ply
 * @date 2024/5/14 14:40
 * @Description TODO
 * 管理配方管理服务
 */
@Service
@RequiredArgsConstructor
public class AdminLumiereFormulaService {

    private final LumiereFormulaService lumiereFormulaService;

    private final LumiereFormulaTypeService lumiereFormulaTypeService;

    private final LumiereFormulaMaterialService lumiereFormulaMaterialService;

    private final LumiereGoodsFormulaCorrelationService lumiereGoodsFormulaCorrelationService;

    private final LumiereFormulaSpecificationsService lumiereFormulaSpecificationsService;

    private final LumiereFormulaSpecificationsDataProportioningService lumiereFormulaSpecificationsDataProportioningService;

    private final LitemallGoodsSpecificationService litemallGoodsSpecificationService;

    private final LitemallGoodsService litemallGoodsService;

    private final LitemallGoodsSpecificationMerchandiseService litemallGoodsSpecificationMerchandiseService;

    private final GoodsReviewService goodsReviewService;

    private final LitemallMerchandiseService litemallMerchandiseService;

    private final LitemallShopService litemallShopService;

    /**
     * 根据查询条件查询配方列表
     * @param lumiereFormula 查询条件
     * @param page 当前页数，默认为1
     * @param limit 每页数量，默认为10
     * @return 配方列表
     */
    public ResponseUtil.Response listLumiereFormula(LumiereFormula lumiereFormula, Integer page, Integer limit) {

       // 构建查询条件
        LambdaQueryWrapper<LumiereFormula> queryWrapper = new LambdaQueryWrapper<>();
        Optional.ofNullable(lumiereFormula.getFormulaName())
                .filter(StringUtils::isNotEmpty)
                .ifPresent(name -> queryWrapper.like(LumiereFormula::getFormulaName, name));

        Optional.ofNullable(lumiereFormula.getFormulaTypeId())
                .filter(id -> id != 0) // 判断formulaTypeId是否不等于0
                .ifPresent(id -> queryWrapper.eq(LumiereFormula::getFormulaTypeId, id));

        Optional.ofNullable(lumiereFormula.getStatus())
                .filter(status -> null != status) // 判断formulaTypeId是否不等于0
                .ifPresent(status -> queryWrapper.eq(LumiereFormula::getStatus, status));

        queryWrapper.orderByAsc(LumiereFormula::getFormulaTypeId).orderByAsc(LumiereFormula::getSort);

        IPage<LumiereFormula> lumiereFormulaList = lumiereFormulaService.page(new Page<>(page,limit),queryWrapper);
        if(lumiereFormulaList.getRecords().size()==0){return ResponseUtil.okPage(lumiereFormulaList);}
        List<AdminLumiereFormulaVO>  resultList = new ArrayList<>();
        for (LumiereFormula formula : lumiereFormulaList.getRecords()) {
            AdminLumiereFormulaVO adminLumiereFormulaVO = new AdminLumiereFormulaVO();
            BeanUtils.copyProperties(formula,adminLumiereFormulaVO);
            //子集
            /*List<LumiereFormulaMaterial> formulaMaterialList = lumiereFormulaMaterialService.list(new LambdaQueryWrapper<LumiereFormulaMaterial>()
                    .eq(LumiereFormulaMaterial::getFormulaId, formula.getId()));*/
            //关联的商品
            List<LumiereGoodsFormulaCorrelation> formulaCorrelationList = lumiereGoodsFormulaCorrelationService.list(new LambdaQueryWrapper<LumiereGoodsFormulaCorrelation>()
                    .eq(LumiereGoodsFormulaCorrelation::getFormulaId, formula.getId()));
            adminLumiereFormulaVO.setGoodsList(CollUtil.isEmpty(formulaCorrelationList)?CollUtil.newArrayList():litemallGoodsService.findByIds(CollStreamUtil.toList(formulaCorrelationList, LumiereGoodsFormulaCorrelation::getGoodsId)));
            adminLumiereFormulaVO.setChildren(new ArrayList<>());
            resultList.add(adminLumiereFormulaVO);
        }
        // 返回结果
        return ResponseUtil.okPage(lumiereFormulaList,resultList);
    }

    /**
     * 根据查询条件查询配方列表
     * @param lumiereFormula 查询条件
     * @return 配方列表
     */
    public ResponseUtil.Response listAllLumiereFormula(LumiereFormula lumiereFormula,Integer page,Integer limit) {
        // 构建查询条件
        LambdaQueryWrapper<LumiereFormula> queryWrapper = new LambdaQueryWrapper<>();

        Optional.ofNullable(lumiereFormula.getStatus())
                .filter(status -> null != status) // 判断formulaTypeId是否不等于0
                .ifPresent(status -> queryWrapper.eq(LumiereFormula::getStatus, status));
        queryWrapper.like(StrUtil.isNotBlank(lumiereFormula.getFormulaName()),LumiereFormula::getFormulaName, StrUtil.trim(lumiereFormula.getFormulaName()));
        queryWrapper.orderByAsc(LumiereFormula::getFormulaTypeId).orderByAsc(LumiereFormula::getAddTime);

        // 返回结果
        return ResponseUtil.okPage(lumiereFormulaService.page(new Page<>(page,limit),queryWrapper));
    }

    /**
     * 根据指定ID获取配方详情。
     * @param id 配方ID
     * @return 包含配方详情的响应结果
     */
    public ResponseUtil.Response details(Integer id){
        return ResponseUtil.ok(lumiereFormulaService.getById(id));
    }

    /**
     * 添加新的配方。
     * @param lumiereFormula 待添加的配方对象
     * @return 添加操作的响应结果
     */
    public ResponseUtil.Response addLumiereFormula(LumiereFormula lumiereFormula) {
        List<LumiereFormula> list = lumiereFormulaService.list();
        // 使用Stream API检查是否存在相同名称的分类
        boolean exists = list.stream()
                .anyMatch(formula ->
                        formula.getFormulaName().equals(lumiereFormula.getFormulaName()));
        // 如果存在相同名称的分类，返回失败响应
        if (exists) {
            return ResponseUtil.fail(FormulaConstants.FORMULA_NAME_EXISTING,"配方名称已存在");
        }
        return lumiereFormulaService.save(lumiereFormula) ? ResponseUtil.ok() : ResponseUtil.fail();
    }

    /**
     * 更新配方信息。
     * @param lumiereFormula 待更新的配方对象
     * @return 更新操作的响应结果
     */
    public ResponseUtil.Response updateLumiereFormula(LumiereFormula lumiereFormula) {
        List<LumiereFormula> list = lumiereFormulaService.list(Wrappers.lambdaQuery(LumiereFormula.class)
                .ne(LumiereFormula::getId,lumiereFormula.getId()));
        // 使用Stream API检查是否存在相同名称的分类
        boolean exists = list.stream()
                .anyMatch(formula ->
                        formula.getFormulaName().equals(lumiereFormula.getFormulaName()));
        // 如果存在相同名称的分类，返回失败响应
        if (exists) {
            return ResponseUtil.fail(FormulaConstants.FORMULA_NAME_EXISTING,"配方名称已存在");
        }
        return lumiereFormulaService.updateById(lumiereFormula) ? ResponseUtil.ok() : ResponseUtil.fail();
    }

    /**
     * 根据指定ID删除配方。
     * @param id 待删除的路配方ID
     * @return 删除操作的响应结果
     */
    public ResponseUtil.Response deleteLumiereFormula(Integer id){
        validateLumiereFormulaIsUse(id);
        return lumiereFormulaService.removeById(id) ? ResponseUtil.ok() : ResponseUtil.fail();
    }

    @VisibleForTesting
    private void validateLumiereFormulaIsUse(Integer id){
        List<LumiereGoodsFormulaCorrelation> goodsFormulaCorrelations = lumiereGoodsFormulaCorrelationService.list(Wrappers.lambdaQuery(LumiereGoodsFormulaCorrelation.class)
                .eq(LumiereGoodsFormulaCorrelation::getFormulaId, id));
        if(goodsFormulaCorrelations.size()>0){
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.LUMIERE_FORMULA_FORMULA_IS_USE);
        }
    }
    /**
     * 添加商品配方关联信息
     * @param lumiereGoodsFormulaCorrelation 商品配方关联信息
     * @return 添加操作的响应结果
     */
    public ResponseUtil.Response addLumiereGoodsFormulaCorrelation(LumiereGoodsFormulaCorrelation lumiereGoodsFormulaCorrelation){
        //删除商品规格的所有数据
//        List<LitemallGoodsSpecification> litemallGoodsSpecificationsList = litemallGoodsSpecificationService.queryByGid(lumiereGoodsFormulaCorrelation.getGoodsId());
//        for (LitemallGoodsSpecification litemallGoodsSpecification : litemallGoodsSpecificationsList) {
//            List<LitemallGoodsSpecificationMerchandise> litemallGoodsSpecificationMerchandisesList = litemallGoodsSpecificationMerchandiseService.queryBySpecid(litemallGoodsSpecification.getId());
//            for (LitemallGoodsSpecificationMerchandise litemallGoodsSpecificationMerchandise : litemallGoodsSpecificationMerchandisesList) {
//                litemallMerchandiseService.findById(litemallGoodsSpecificationMerchandise.getMerchandiseId());
//            }
//        }

        // 获取商品规格列表
        //获取商品的规格列表
        List<LitemallGoodsSpecification> litemallGoodsSpecificationsList = litemallGoodsSpecificationService.queryByGid(lumiereGoodsFormulaCorrelation.getGoodsId());
        // 遍历商品规格列表并删除所有关联的商品和规格
        litemallGoodsSpecificationsList.forEach(spec -> {
            // 获取关联的商品列表并删除

            /*litemallGoodsSpecificationMerchandiseService.queryBySpecid(spec.getId())
                    .forEach(merch -> {
                        // 获取商品并删除
                        LitemallMerchandise merchandise = litemallMerchandiseService.findById(merch.getMerchandiseId());
                        if (merchandise != null) {
                            litemallMerchandiseService.deleteById(merchandise);
                        }
                    });*/
            // 删除商品规格关联
            litemallGoodsSpecificationMerchandiseService.deleteBySpecId(spec.getId());
            // 删除商品规格
            litemallGoodsSpecificationService.deleteById(spec.getId());
        });

        //查询是否已存在数据
        LumiereGoodsFormulaCorrelation goodsFormulaCorrelation = lumiereGoodsFormulaCorrelationService.getOne(new LambdaQueryWrapper<LumiereGoodsFormulaCorrelation>().eq(LumiereGoodsFormulaCorrelation::getGoodsId, lumiereGoodsFormulaCorrelation.getGoodsId()));
        if (ObjectUtils.isEmpty(goodsFormulaCorrelation)){
            return lumiereGoodsFormulaCorrelationService.save(lumiereGoodsFormulaCorrelation)? ResponseUtil.ok() : ResponseUtil.fail();
        }else{
            goodsFormulaCorrelation.setFormulaId(lumiereGoodsFormulaCorrelation.getFormulaId());
            return lumiereGoodsFormulaCorrelationService.updateById(goodsFormulaCorrelation)? ResponseUtil.ok() : ResponseUtil.fail();
        }
    }

    public ResponseUtil.Response  unbundleLumiereGoodsFormulaCorrelation(LumiereGoodsFormulaCorrelation lumiereGoodsFormulaCorrelation) {
        // 查询是否已存在数据
        LumiereGoodsFormulaCorrelation goodsFormulaCorrelation = lumiereGoodsFormulaCorrelationService.getOne(
                new LambdaQueryWrapper<LumiereGoodsFormulaCorrelation>()
                        .eq(LumiereGoodsFormulaCorrelation::getGoodsId, lumiereGoodsFormulaCorrelation.getGoodsId())
        );
        // 如果不存在关联数据，直接返回成功
        if (ObjectUtils.isEmpty(goodsFormulaCorrelation)) {
            return ResponseUtil.ok();
        }
        // 获取商品信息
        LitemallGoods litemallGoods = litemallGoodsService.findById(goodsFormulaCorrelation.getGoodsId());
        // 如果商品正在售卖，抛出异常
        if (litemallGoods.getIsOnSale()) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.LUMIERE_GOODS_NOT_REMOVED);
        }
        // 删除关联数据并返回结果
        lumiereGoodsFormulaCorrelationService.removeById(goodsFormulaCorrelation);
        goodsReviewService.againApprove(new GoodsReviewDto().setId(lumiereGoodsFormulaCorrelation.getGoodsId()).setGoodsSn(litemallGoods.getGoodsSn()).setGoodsName(litemallGoods.getName())
                .setContent("解除配方,进行反审核"));
        return ResponseUtil.ok();
    }

    /**
     * 通过商品查询配方规格列表
     * @param goodsId 查询条件
     * @return 配方列表
     */
    public ResponseUtil.Response getGoodsFormulaSpecifications(Integer goodsId){
        LumiereGoodsFormulaCorrelation goodsFormulaCorrelation = lumiereGoodsFormulaCorrelationService.getOne(new LambdaQueryWrapper<LumiereGoodsFormulaCorrelation>().eq(LumiereGoodsFormulaCorrelation::getGoodsId, goodsId));
        if (!ObjectUtils.isEmpty(goodsFormulaCorrelation)){
            LumiereFormula lumiereFormula = lumiereFormulaService.getById(goodsFormulaCorrelation.getFormulaId());
            List<LumiereFormulaSpecifications> formulaSpecifications = lumiereFormulaSpecificationsService.list(new LambdaQueryWrapper<LumiereFormulaSpecifications>().eq(LumiereFormulaSpecifications::getFormulaId, goodsFormulaCorrelation.getFormulaId()).orderByDesc(LumiereFormulaSpecifications::getIsDefault));

            GoodsFormulaSpecificationsVO goodsFormulaSpecificationsVO = new GoodsFormulaSpecificationsVO()
                    .setGoodsFormulaName(lumiereFormula.getFormulaName())
                    .setGoodsFormulaSpecifications(formulaSpecifications);

            return ResponseUtil.ok(goodsFormulaSpecificationsVO);
        }else{
           return ResponseUtil.ok(new GoodsFormulaSpecificationsVO());
        }
    }

    /**
     * 通过商品id查询商品配方关联表的配方详细数据
     * @param goodsId 查询条件
     * @return 配方列表
     */
    public ResponseUtil.Response getGoodsFormulaCorrelationDetails(Integer goodsId){
        LumiereGoodsFormulaCorrelation goodsFormulaCorrelation = lumiereGoodsFormulaCorrelationService.getOne(new LambdaQueryWrapper<LumiereGoodsFormulaCorrelation>().eq(LumiereGoodsFormulaCorrelation::getGoodsId, goodsId));
        if(!ObjectUtils.isEmpty(goodsFormulaCorrelation)){
            LumiereFormula formula = lumiereFormulaService.getById(goodsFormulaCorrelation.getFormulaId());
            AdminLumiereFormulaVO adminLumiereFormulaVO = new AdminLumiereFormulaVO();
            BeanUtils.copyProperties(formula,adminLumiereFormulaVO);

            LumiereFormulaType formulaType = lumiereFormulaTypeService.getById(formula.getFormulaTypeId());
            adminLumiereFormulaVO.setType(formulaType.getType());
            //子集
            List<LumiereFormulaMaterial> formulaMaterialList = lumiereFormulaMaterialService.list(new LambdaQueryWrapper<LumiereFormulaMaterial>()
                    .eq(LumiereFormulaMaterial::getFormulaId, formula.getId()));
            adminLumiereFormulaVO.setChildren(formulaMaterialList);
            return ResponseUtil.ok(adminLumiereFormulaVO);
        }else{
            return null;
        }
    }


    /**
     * 复制配方
     * @param id
     * @return
     */
    public ResponseUtil.Response copyLumiereFormula(Integer id) {
        // 获取配方数据
        LumiereFormula formula = lumiereFormulaService.getById(id);
        if (formula == null) {
            throw new IllegalArgumentException("配方不存在");
        }

        // 构建副本名称
        String baseName = formula.getFormulaName() + " - 副本";
        String newName = baseName;

        // 检查是否已有同名的副本
        List<LumiereFormula> existingCopies = lumiereFormulaService.list(
                Wrappers.lambdaQuery(LumiereFormula.class)
                        .likeRight(LumiereFormula::getFormulaName, baseName)
        );

        // 如果已有副本，递增编号
        if (!existingCopies.isEmpty()) {
            // 查找现有副本的最大编号
            int maxCopyNumber = existingCopies.stream()
                    .map(form -> {
                        String name = form.getFormulaName();
                        // 提取副本编号
                        int idx = name.lastIndexOf(" ");
                        if (idx != -1) {
                            try {
                                return Integer.parseInt(name.substring(idx + 1));
                            } catch (NumberFormatException e) {
                                return 0;  // 处理没有编号的情况
                            }
                        }
                        return 0;
                    })
                    .max(Integer::compare)
                    .orElse(0);

            // 新的副本名称加1
            newName = baseName + " " + (maxCopyNumber + 1);
        }

        // 创建新配方副本，复制配方数据
        LumiereFormula newFormula = new LumiereFormula();
        BeanUtils.copyProperties(formula,newFormula);
        newFormula.setId(null);
        newFormula.setTemplate(false);
        newFormula.setFormulaName(newName);  // 使用递增后的名称
        newFormula.setStatus(0);
        // 设置其他需要的字段（注意避免ID冲突等问题）
        lumiereFormulaService.save(newFormula);  // 保存新配方

        // 获取配方规格列表
        List<LumiereFormulaSpecifications> formulaSpecifications = lumiereFormulaSpecificationsService.list(
                Wrappers.lambdaQuery(LumiereFormulaSpecifications.class).eq(LumiereFormulaSpecifications::getFormulaId, id)
        );

        // 遍历配方规格
        for (LumiereFormulaSpecifications formulaSpecification : formulaSpecifications) {
            // 创建新规格副本
            LumiereFormulaSpecifications newFormulaSpecification = new LumiereFormulaSpecifications();
            BeanUtils.copyProperties(formulaSpecification,newFormulaSpecification);
            newFormulaSpecification.setId(null);
            newFormulaSpecification.setFormulaId(newFormula.getId());  // 关联到新配方
            newFormulaSpecification.setSpecificationsName(formulaSpecification.getSpecificationsName());
            // 设置其他需要的字段
            lumiereFormulaSpecificationsService.save(newFormulaSpecification);  // 保存新规格

            // 获取配方规格的原料比例数据
            List<LumiereFormulaSpecificationsDataProportioning> formulaSpecificationsDataProportionings = lumiereFormulaSpecificationsDataProportioningService.list(
                    Wrappers.lambdaQuery(LumiereFormulaSpecificationsDataProportioning.class).eq(LumiereFormulaSpecificationsDataProportioning::getFormulaSpecificationsId, formulaSpecification.getId())
            );

            // 遍历每个原料比例数据并创建新副本
            List<LumiereFormulaSpecificationsDataProportioning> lumiereFormulaSpecificationsDataProportioningList = new ArrayList<>(formulaSpecificationsDataProportionings.size());
            for (LumiereFormulaSpecificationsDataProportioning proportioning : formulaSpecificationsDataProportionings) {
                LumiereFormulaSpecificationsDataProportioning newProportioning = new LumiereFormulaSpecificationsDataProportioning();
                BeanUtils.copyProperties(proportioning,newProportioning);
                newProportioning.setId(null);
                newProportioning.setFormulaSpecificationsId(newFormulaSpecification.getId());  // 关联到新的配方规格
                // 设置其他需要的字段
                lumiereFormulaSpecificationsDataProportioningList.add(newProportioning);
            }
            lumiereFormulaSpecificationsDataProportioningService.saveBatch(lumiereFormulaSpecificationsDataProportioningList);  // 保存新配方原料比例数据

        }
        return ResponseUtil.ok();
    }


}
